import { useMemo } from 'react'
import useWidget from '@/hooks/useWidget'
import Chart from '../index'

function useChartDataInfo(widgetId) {
  const { currentWidget } = useWidget(widgetId)
  const data = currentWidget?.status?.data || []
  const queryFields = currentWidget?.query?.queryFields || {}
  const type = currentWidget?.type
  const requestFields = Chart.getRequestFields(type)

  const indexToFieldArray = useMemo(() => {
    const arr = []
    Object.entries(queryFields).forEach(([key, item]) => {
      if (key === 'filter') return
      item.forEach((v) => {
        arr.push(v.id)
      })
    })
    return arr
  }, [queryFields])

  const keyToFieldObject = useMemo(() => {
    const obj = {}
    Object.entries(requestFields).forEach(([rowKey, row]) => {
      const role = row.role || 'other'
      const fields = queryFields[rowKey]
      fields && (obj[`${role}Key`] = fields)
    })
    return obj
  }, [queryFields])

  const roleKeys = useMemo(() => {
    const obj = {}
    Object.entries(keyToFieldObject).forEach(([key, value]) => {
      if (value && value.length) {
        obj[key] = value[0].id
      }
    })
    return obj
  }, [keyToFieldObject])

  return { data, keyToFieldObject, indexToFieldArray, ...roleKeys }
}

export default useChartDataInfo
